<template>
  <div class="editPassword clearfloat">
    <h1 class="editPassword-title tc">修改密码</h1>
    <el-steps :active="active" align-center>
      <el-step title="" description=""></el-step>
      <el-step title="" description=""></el-step>
      <el-step title="" description=""></el-step>
    </el-steps>

    <div class="editPassword-contents">
      <div v-if="active == 1" class="form">
        <el-form :model="phoneForm" :rules="phoneFormRules" ref="phoneForm" label-width="80px" label-position="left">
          <el-form-item label="手机号" prop="phone">
            <el-input  v-model="phoneForm.phone" autocomplete="off" class="phone">
              <template slot="append">
                <el-button  
                  v-no-more-click:3000
                  :disabled="btnIsDisabled"
                  class="btn-code"
                  type="primary"
                  @click="getVCode('phoneForm')">{{VCodeText}}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <div class="code" >
              <div 
                v-for="index in 6" 
                :key="index"
                @click="getFocus(index)"                
                ref="codeInputItem"
                class="code-input-item">
                {{phoneForm.code[index-1]}}
              </div>
              <el-input v-model="phoneForm.code" autocomplete="off" :maxlength="6" ref="codeInput" ></el-input>
            </div>
            
          </el-form-item>
        </el-form>
      </div>
      <div v-else-if="active == 2" class="form passwordForm">
        <el-form :model="pwdForm" :rules="pwdFormRules" ref="pwdForm" label-width="120px" label-position="left">
          <el-form-item label="输入新密码" prop="newPwd">
            <el-input type="password" show-password v-model="pwdForm.newPwd" autocomplete="off" class="pwd"></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirmPwd">
            <el-input type="password" show-password v-model="pwdForm.confirmPwd" autocomplete="off" class="pwd" ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div v-else class="success">
        <i class="el-icon-check"></i>
      </div>
      <div class="btns clearfloat" v-if="active != 3">
        <el-button type="primary" class="fr submit" @click="next()">下一步</el-button>
        <el-button type="primary" plain class="fr cancel" @click="cancel">取消</el-button>
      </div>
    </div>

  </div>
</template>

<script>

export default {
  data () {
    let that = this;
    var validateConfirmPwd = function(rule, value, callback) {
      if (value === '') {
        callback(new Error('请填写新密码'));
      }else if (value !== that.pwdForm.newPwd) {
        callback(new Error('两次密码不一致'));
      }else {
        callback();
      }
    }
    var validatePhone = function(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入手机号'));
      } else if (!(/^1[3456789]\d{9}$/.test(value))) {
        callback(new Error('请输正确的手机号'));
      } else if (value != that.$store.state.user.phone) {
        callback(new Error('请输入你绑定的手机号'));
      } else {
        callback();
      }
    }
    return {
      active: 1,
      phoneForm: {
        phone: '',
        code: ''
      },
      pwdForm: {
        newPwd: '',
        confirmPwd: ''
      },
      phoneFormRules: {
        phone: [
          { required: true, validator: validatePhone, trigger: 'change' }
        ],
        code: [
          { required: true,  message: "请输入验证码", trigger: 'change' }
        ]
      },
      pwdFormRules: {
        newPwd: [
          {
            required: true,
            message: "请输入新密码",
            trigger: "change"
          },
          {
            min: 6,
            max: 12,
            message: "密码长度为6-12位",
            trigger: "change"
          }
        ],
        confirmPwd: [
          {
            required: true,
            validator: validateConfirmPwd,
            trigger: "change"
          },
          {
            min: 6,
            max: 12,
            message: "密码长度为6-12位",
            trigger: "change"
          }
        ]
      },
      VCodeText:"发送验证码",
      btnIsDisabled: false,
    }
  },
  watch: {
    // "phoneForm.code": {
    //   handler: function (val) {
    //     let doms = this.$refs['codeInputItem']
    //     for(let i = 0 ; i < doms.length; i++) {
    //       if (val.length == 6) {
    //         doms[i].classList.add('isValue')
    //       } else if (val == '') {
    //         doms[i].classList.remove("isValue")
    //       } else {
    //         if (doms[i].innerText != '') {
    //           doms[i].classList.add('isValue')
    //         } else {
    //           doms[i].classList.remove("isValue")
    //         }
    //       }
          
    //     }
        
    //   },
    //   deep: true,
    // }
  },
  
  methods:{
    getVCode(formName) {
      this.$refs[formName].validateField('phone', valid => {
        if(!valid) {
          if (this.btnIsDisabled) {
          } else {
            this.getVCodeRequest()
          }
        } else {
          return false
        }
      })

    },
    getVCodeRequest () {
      let that = this;
      let params = {
        phone: this.phoneForm.phone,
        type: 2,
        // guard:
      }
      that.$axios.post("/api/captcha",params).then(res => {
        if (res.data.code == 200) {
          that.$message({
            message: "验证码发送成功！",
            type: "success"
          })
          let num = 60;
          that.btnIsDisabled = true;
          let timer = setInterval(function() {
            
            that.VCodeText = num + "秒后可重新发送";
            num -= 1;
            if (num < 0) {
              that.VCodeText = "发送验证码";
              that.btnIsDisabled = false;
              clearInterval(timer);
            }
          }, 1000);
        } else {
          if (res.data.code == 400) {
            that.$message({
              message: res.data.message,
              type: "error"
            })

          } else {
            that.$message({
              message: "验证码发送失败！",
              type: "error"
            })
          }
        }
      })
    },
    getFocus (index) {
      this.$refs['codeInput'].focus()
    },
    next () {
      let formName = null
      if (this.active == 1) {
        formName = 'phoneForm'
      }  else if (this.active == 2) {
        formName = 'pwdForm'
      }

      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {}
          if (this.active == 1) {
            params =  {
              guard: 'company',
              phone: this.phoneForm.phone,
              code: this.phoneForm.code,
            }
            this.validationCode(params)
          } else if (this.active == 2) {
            params = {
              guard: 'company',
              password: this.pwdForm.newPwd
            }
            this.validationPwd(params)
          } 
        } else {
          return false
        }
      })
      
    },
    cancel () {
      // this.$refs['phoneForm'].resetFields()
      // this.$refs['pwdForm'].resetFields()
      this.$router.push({path:'/company/home'})
    },
    validationCode (params) {
      this.$axios.get('api/company/verify_phone', {params:params}).then( res => {
        if (res.data.code == '200') {
          this.active++
        } else {
          this.$alert(res.data.message, '提示', {
            confirmButtonText: '确定',
            center: true,
            callback: action => {
            }
          })
        }
      })
    },
    validationPwd (params) {
      this.$axios.put(`api/company/change_pwd/${this.$store.state.user.id}`,params).then( res => {
        if (res.data.code == '200') {
          this.active++
          let that = this
          setTimeout(() => {
            that.quit()
          }, 1000)
        } else {
          this.$alert(res.data.message, '提示', {
            confirmButtonText: '确定',
            center: true,
            callback: action => {
            }
          })
        }
      })
    },
    quit() {
      this.$message.success("密码修改成功")
     
      this.$store.commit("delToken")
      this.$cookies.remove("token")
      this.$store.commit("delUser")
      this.$cookies.remove("user")
      if(process.client) {
        window.localStorage.setItem('auto_login', JSON.stringify(false))
      }
      this.$router.push({
        path: '/companyLogin'
      });
    }
  }
}
</script>

<style lang='less'>
  .editPassword {
    width: 100%;
    height: 100%;
    padding-top: 60px;
    background: #fff;

    box-sizing: border-box;

    &-title {
      font-size: 20px;
    }
    .el-steps {
      width: 310px;
      margin: 30px auto 0;
      .el-step {
        .el-step__head {
          .el-step__line {
            background-color: #41aaff;
            height: 1px;
          }
          .el-step__icon.is-text {
            border: 1px solid;
          }
        }
        .is-finish {
          .el-step__line {
            background-color: #41aaff;
          }
          .el-step__icon {
            background: #249dff;
            color: #fff;
          }
        }
        .is-process {
          color: #2ba0ff;
          border-color: #2ba0ff;
        }
        .is-wait {
          color: #2ba0ff;
          border-color: #2ba0ff;
        
        }
      }
    }
    &-contents {
      width: 100%;

      .form {
        margin: 35px auto 0;
        width: 400px;
        .el-form {
          .el-form-item {
            margin-bottom: 40px;
            .el-form-item__label {
              font-size: 15px;
            }
          }
          .phone {
            width: 320px;

            .el-input__inner {
              border:1px solid rgba(191,191,191,1);
              border-radius:5px;
              border-right: 0;
              border-right: 0;
              border-top-right-radius: 0;
              border-bottom-right-radius: 0;
            }
            .el-input-group__append {
              border-top-left-radius: 5px;
              border-bottom-left-radius: 5px;
              background:rgba(36,157,255,1);
              border-radius:5px;
              color: #FFF;
              border: 0px;

              .el-button {
                padding: 13px 20px;
              }
            }
          }
          .code {
            width: 320px;
            display: flex;
            flex-direction: row;
            justify-content: space-between;

            @keyframes blink {
              0%, 100% {
                background-color: #000;
                }
              50% {
                background-color: transparent;
              } 
            }
            .code-input-item {
              width:40px;
              height:30px;
              border-bottom:1px solid rgba(191,191,191,1);
              // border-radius:5px;
              text-align: center;
              padding-bottom: 0;
              color:rgba(57,57,57,1);
              font-size:15px;
              z-index: 99;
              position: relative;
            }
            .isValue {
              background:rgba(248,248,248,1);
            }

            .animation::after {
              position: absolute;
              content: '';
              display: inline-block;
              width: 2px;
              height: 18px;
              top: 50%;
              transform: translateY(-50%);
              animation: blink 1.2s infinite steps(1, start);
            }

            .el-input {
              position: absolute;
              width: 320px;
              left: 0;
              
              .el-input__inner {
                color: transparent;
                text-shadow: 0 0 0 transparent;
                outline: none;
                border: 0;
                padding: 0 0;

                // margin-left: -100%;
              }
              .el-input__inner::selection {
                  background:#FFF;
              }
              .el-input__inner::-moz-selection {
                  background:#FFF;
              }
              .el-input__inner::-webkit-selection {
                  background:#FFF;
              }
            }

          }
        }
      }
      .btns {
        margin-top: 40px;
        padding-right: 73px;
        .el-button {
          margin-left: 0;
          margin-right: 20px;
          padding: 8px 22px 8px 22px;
          font-size: 15px;
          border-radius: 5px;
        }
        

        .submit {
          background: #249DFF;
          color: #fff;
          margin-right: 0;
        }
        .cancel {
          border:1px solid rgba(36,157,255,1);
          background:rgba(255,255,255,1);
          color: #249DFF;
        }
      }
      .success {
        width: 115px;
        height: 115px;
        margin: 35px auto;
        background: #529144;
        border-radius: 50%;
        position: relative;
        i {
          position:absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          font-size: 80px;
          color: #fff;
          
        }
      }
    }
  }
</style>